package com.tsing.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tsing.common.result.PageResult;
import com.tsing.common.result.Result;
import com.tsing.pojo.entity.TlPost;
import com.tsing.pojo.vo.ArticleDetailsVO;
import com.tsing.pojo.vo.CommentDetailsVO;
import com.tsing.service.SearchService;
import com.tsing.service.impl.SearchServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * @auth 卢孝宇
 * @date 2023/12/14 14:24
 */
public class SearchController {

    private SearchService searchService = new SearchServiceImpl();
    public Result<List<TlPost>> list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;utf-8");

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonRequest = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonRequest.append(line);
        }

        JSONObject jsonObject = JSON.parseObject(jsonRequest.toString());

        String query = jsonObject.getString("query");
        query = (query != null && !query.isEmpty()) ? query : null;

        List<TlPost> result = searchService.list(query);

        return Result.success(result);
    }

    public PageResult<ArticleDetailsVO> postList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;utf-8");

        // 获取请求体数据
        BufferedReader reader = request.getReader();
        StringBuilder jsonRequest = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonRequest.append(line);
        }

        JSONObject jsonObject = JSON.parseObject(jsonRequest.toString());

        String query = jsonObject.getString("query");
        query = (query != null && !query.isEmpty()) ? query : null;

        Long userId = jsonObject.getLong("userId");
        userId = (userId != null && userId>0) ? userId :null ;

        Integer page = jsonObject.getInteger("page");
        page = (page != null && page>0) ? page : 1;

        Integer size = jsonObject.getInteger("size");
        size = (size != null && size>0) ? size : 10;

        PageResult<ArticleDetailsVO> result = searchService.postList(query,page,size,userId);

        return result;
    }
}
